package com.xinpujing.caiji.service;

import com.alibaba.fastjson.JSONObject;
import com.xinpujing.caiji.dto.api68.Api68Dto;
import com.xinpujing.caiji.dto.api68.Data;
import com.xinpujing.caiji.enums.LotteryTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.SocketTimeoutException;

import static com.xinpujing.caiji.util.HttpUtils.getString;

public class Api68Service {
    private static Logger logger = LoggerFactory.getLogger(Api68Service.class);

    private CommonService commonService;

    public void insertIfNotExist(String url , LotteryTypeEnum typeEnum){
        int type = typeEnum.getType();
        if(url.equals("")){
            logger.info("url is null , ignore , type {}" , typeEnum.getName());
            return;
        }
        if(type == 0){
            logger.info("type is 0 , ignore , url {} name {} " , url , typeEnum.getName());
            return;
        }
        String jsonStr = null;
        try{
            jsonStr = getString(url);
        }catch (SocketTimeoutException e){
            logger.error("socket time out .. {}" , url );
            return;
        }

        Api68Dto api68Dto = JSONObject.parseObject(jsonStr , Api68Dto.class);
        Data result = api68Dto.getResult().getData();
        String number  = result.getPreDrawIssue();
        String data = result.getPreDrawCode();
        String time = result.getPreDrawTime();

//        synchronized (this){
//
//        }
        Boolean exist = commonService.exist(type  , number , data );
        if(exist){
            logger.trace(" 开奖数据已存在 ..type {}  , number {} , data {}  " , type  , number , data);
            return;
        }
        commonService.insert(type ,  time , number , data );
        logger.info(" 开奖数据已录入 ..type {}  , time {} , number {} , data {}  " , typeEnum.getName() , time , number , data);

    }

    public CommonService getCommonService() {
        return commonService;
    }

    public void setCommonService(CommonService commonService) {
        this.commonService = commonService;
    }
}
